package com.zhuchang.self_rpc.test.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @Author RenPu
 * @Date 2021/8/18 11:12
 * @Version 1.0
 * @Description: 编码器
 **/
public class RpcEncoder extends MessageToByteEncoder {

    //所要编码对象的类型
    private Class<?> genericClass;

    public RpcEncoder(Class<?> genericClass) {
        this.genericClass = genericClass;

    }


    /**
     * 编码方法：
     * 1：把java对象进行编码
     * 2：写入buff内
     * 3：写出到server端
     *
     * @param channelHandlerContext
     * @param msg
     * @param out
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf out) throws Exception {

        if (genericClass.isInstance(msg)) {

            //进行编码
            byte[] data = Serializationer.serialize(msg);

            //消息：包头：数据包的长度，包体：数据的内容
            out.writeInt(data.length);
            out.writeBytes(data);

        }


    }
}
